const fs = require('fs');
const { DownloadStatus, isFinishStatus } = require('../../common/DownloadStatus');

class DownloadStateManager {
    constructor(dbPath) {
        try {
            this.videos = JSON.parse(fs.readFileSync(dbPath)).map(v => {
                // 修正状态
                if (!isFinishStatus(v.statusCode)) {
                    v.statusCode = DownloadStatus.Stopped;
                }
                return v;
            });
        } catch (error) {
            console.error('初始化视频列表异常', error);
            this.videos = [];
        }
        this.activeTasks = new Map();
        this.dbPath = dbPath;
    }

    addVideo(video) {
        video.statusCode = video.statusCode || DownloadStatus.Init;
        video.downloadType = video.downloadType || 'mp4'; // 默认类型为mp4
        this.videos.unshift(video);
        this._saveToDB();
        return video;
    }

    getVideo(id) {
        return this.videos.find(v => v.id === id);
    }

    updateStatus(id, status, statusCode) {
        const video = this.getVideo(id);
        if (video) {
            video.status = status;
            video.statusCode = statusCode;
            this._saveToDB();
        }
        return video;
    }

    completeVideo(id, filePath) {
        const video = this.getVideo(id);
        if (video) {
            video.status = "已完成";
            video.statusCode = DownloadStatus.Success;
            video.videopath = filePath;
            this._saveToDB();
        }
        return video;
    }

    failVideo(id, error) {
        const video = this.getVideo(id);
        if (video) {
            video.status = error.message || "下载失败";
            video.statusCode = DownloadStatus.DownloadFail;
            this._saveToDB();
        }
        return video;
    }

    addTask(id, task) {
        this.activeTasks.set(id, task);
    }

    stopTask(id) {
        const task = this.activeTasks.get(id);
        if (!task) {
            return;
        }
        task.stop();
        this.updateStatus(id, "停止中...", DownloadStatus.Stopping);
    }

    removeTask(id) {
        this.activeTasks.delete(id);
    }

    stopAllTasks() {
        this.activeTasks.forEach((task, id) => {
            task.stop();
            this.updateStatus(id, "已停止", DownloadStatus.Stopped);
        });
        this.activeTasks.clear();
    }

    removeVideo(id) {
        const index = this.videos.findIndex(v => v.id === id);
        if (index !== -1) {
            this.videos.splice(index, 1);
            this._saveToDB();
        }
        this.activeTasks.delete(id);
        return index !== -1;
    }

    _saveToDB() {
        fs.writeFileSync(this.dbPath, JSON.stringify(this.videos));
    }
}

module.exports = { DownloadStateManager };
